#!/usr/bin/env python3
"""
参数管理系统客户端包构建脚本
"""
import subprocess
import sys
import os
import shutil


def run_command(command, description):
    """运行命令并显示结果"""
    print(f"\n{'='*50}")
    print(f"执行: {description}")
    print(f"命令: {command}")
    print('='*50)
    
    try:
        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
        print("✅ 成功")
        if result.stdout:
            print("输出:")
            print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print("❌ 失败")
        print(f"错误: {e}")
        if e.stdout:
            print("标准输出:")
            print(e.stdout)
        if e.stderr:
            print("错误输出:")
            print(e.stderr)
        return False


def clean_build_dirs():
    """清理构建目录"""
    dirs_to_clean = ['build', 'dist', '*.egg-info']
    for pattern in dirs_to_clean:
        if os.path.exists(pattern):
            if os.path.isdir(pattern):
                shutil.rmtree(pattern)
                print(f"清理目录: {pattern}")
            else:
                os.remove(pattern)
                print(f"清理文件: {pattern}")


def main():
    """主函数"""
    print("参数管理系统客户端包构建")
    print("="*60)
    
    # 检查当前目录
    if not os.path.exists("setup.py"):
        print("❌ 请在包根目录下运行此脚本")
        return 1
    
    # 1. 清理构建目录
    print("\n1. 清理构建目录")
    clean_build_dirs()
    
    # 2. 构建源码包
    if not run_command("python setup.py sdist", "构建源码包"):
        return 1
    
    # 3. 构建wheel包
    if not run_command("python setup.py bdist_wheel", "构建wheel包"):
        return 1
    
    # 4. 显示构建结果
    print("\n" + "="*60)
    print("构建结果:")
    print("="*60)
    
    if os.path.exists("dist"):
        print("构建的文件:")
        for file in os.listdir("dist"):
            file_path = os.path.join("dist", file)
            size = os.path.getsize(file_path)
            print(f"  {file} ({size} bytes)")
    
    print("\n安装说明:")
    print("1. 本地安装:")
    print("   pip install dist/param_management_client-1.0.0-py3-none-any.whl")
    print("\n2. 从源码安装:")
    print("   pip install dist/param-management-client-1.0.0.tar.gz")
    print("\n3. 上传到PyPI:")
    print("   twine upload dist/*")
    
    print("\n🎉 包构建完成！")
    
    return 0


if __name__ == "__main__":
    sys.exit(main())
